<?php
/***
 * Candy框架 框架日志类
 * 
 * $Author: 刘森 (fingerboy@qq.com) $
 * $Date: 2019-11-16 15:57:48 $   
 */

declare (strict_types = 1);
namespace Candy\Core;

defined('CANDY') OR die('You Are A Bad Guy. o_O???');

final Class Log {
    private static $_handle= [];  //文件句柄
	
	/**
     * 写日志
	 *
     * @param data $data 写入的数据
     * @param str $path 记录文件名称
     * @param int $type 日志等级 -1:无等级  0:DEBUG调试 1:INFO正常  2:WARN警告 3:ERROR错误 4:FATAL致命错误   默认0
     */
    public static function input($data,int $type = 0,string $path = null): void
	{
        $log_path = $path ?: LOGPATH . date("Y-m-d").'.log';
        \Candy\Extend\Dir::create(dirname($log_path) . '/');
        if(!isset(self::$_handle[$log_path])){
            self::$_handle[$log_path] = @fopen($log_path, 'a');
        }
        $desctitle=($type==-1)?'':'['.self::getDescTitle($type).']:';
        $fineStamp = date('Y-m-d H:i:s') . substr(microtime(), 1, 9);
        fwrite(self::$_handle[$log_path], strtoupper('['.$fineStamp.']') . $desctitle . self::getRequest($data));
		
		//关闭写入
		self::close($log_path);
    }
	
	/**
     * 读日志
	 *
     * @param str $path 记录文件名称
     */
    public static function read(string $path=null,bool $display=false):mixed
	{
        $log_path = $path ?: LOGPATH . date("Y-m-d").'.log';
		$log_content = '';
		if(is_file($log_path)){
			$log_content = file_get_contents($log_path);
			$list_str_array = explode(PHP_EOL, $log_content);
			$log_content = '';
			if($display){
				$total_lines = sizeof($list_str_array);
				$log_content .= '<table width="85%" border="0" cellpadding="0" cellspacing="1" style="background:#0478CB; font-size:12px; line-height:25px;">';
				foreach ($list_str_array as $key=>$lines_str) {
					if($key == $total_lines - 1) continue;
					$bg_color = ($key % 2 == 0) ? '#FFFFFF' : '#C6E7FF';
					$log_content .= '<tr><td height="25" align="left" bgcolor="' . $bg_color .'">&nbsp;' . $lines_str . '</td></tr>';
				}
				$log_content .= '</table>';
			}else{
				return $list_str_array;
			}	
		}
		return $log_content;
    }
    
    /**
     * 将数组或者对象转换成字符串
	 *
     * @param unknown $request
     * @return string
     */
    private static function getRequest($request): string
	{
        if(!is_string($request)){
            if(is_resource($request)){
                $request='resource(N) of type (stream)';
            }else{
				if(!is_string($request)){
					$request=var_export($request,true);
				}
            }
        }
        return $request.PHP_EOL;
    }
    /**
     * 转换日志等级描述
     */
    private static function getDescTitle(int $type): string
	{
        $title='DEBUG';
        switch($type){
            case 1:
                $title='INFO';
                break;
            case 2:
                $title='WARN';
                break;
            case 3:
                $title='ERROR';
                break;
            case 4:
                $title='FATAL';
                break;
            default:
                break;
        }
        return $title;
    }
	
    /**
     * 关闭文件句柄
     */
    private static function close(string $val): void
	{
		if(!isset(self::$_handle[$val])){
            @fclose(self::$_handle[$val]);
        }
    }
}
